package com.leven.easyerp.dao.impl;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.leven.easyerp.dao.BaseDao;
import com.leven.easyerp.entity.Page;

/**
 * 所有Dao实现类的基类
 * 
 * @author Leven.Chen
 */
public abstract class BaseDaoImpl extends HibernateDaoSupport implements BaseDao {
	@Autowired
	public void setSessionFactoryOverride(SessionFactory sessionFactory) {
		super.setSessionFactory(sessionFactory);
	}

	@Override
	public <T> T get(Class<T> clazz, Serializable id) {
		return getHibernateTemplate().get(clazz, id);
	}

	@Override
	public <T> Serializable create(T entity) {
		return getHibernateTemplate().save(entity);
	}

	@Override
	public <T> void update(T entity) {
		getHibernateTemplate().update(entity);
	}

	@Override
	public <T> void delete(T entity) {
		getHibernateTemplate().delete(entity);
	}

	@Override
	public <T> void deleteById(Class<T> clazz, Serializable id) {
		T t = getHibernateTemplate().get(clazz, id);
		if (t != null) {
			getHibernateTemplate().delete(t);
		}
	}

	@Override
	public <T> List<T> findObject(String hql, Object[] args) {
		return findObject(hql, args, 0, 0);
	}

	@Override
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public <T> List<T> findObject(final String hql, final Object[] args, int pageNo, int pageSize) {
		Page<T> page = new Page<T>(pageNo, pageSize);
		final int start = page.getFirst();
		final int max = page.getPageSize();
		final boolean isPaging = (max > 0);
		HibernateTemplate hibernateTemplate = getHibernateTemplate();
		List<T> dataList = hibernateTemplate.executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				Query query = session.createQuery(hql);
				// 分页的情况
				if (isPaging) {
					query.setFirstResult(start).setMaxResults(max);
				}
				if (args != null) {
					for (int i = 0, j = args.length; i < j; i++) {
						query.setParameter(i, args[i]);
					}
				}
				return query.list();
			}
		});
		return dataList;
	}

	@Override
	public int countObject(String hql, String[] paramNames, Object[] values) {
		Object obj = getHibernateTemplate().findByNamedParam(hql, paramNames, values);
		return Integer.valueOf(obj.toString());
	}

}
